import React, { RefObject } from 'react';
import { connect } from 'react-redux';
import styles from 'src/pages/DataManage/DataDispatch/index.module.scss';
import { Button, Col, Row, Input, Table, Space, Tooltip, Popconfirm, message, Typography } from 'antd';

import { SearchOutlined, PlusCircleOutlined, FormOutlined, DeleteOutlined, StopOutlined,RightCircleOutlined,FontSizeOutlined,FileFilled, SendOutlined } from '@ant-design/icons';

import { createModel, deleteModel, getArrangeList, activeModel, rJob, getModelTree, triggerModel } from 'src/services/DataManage';
import { CreateModalComponent } from './components/CreateModal/index';
import { CreateFile } from 'src/pages/DataManage/DataDispatch/components/CreateFile';
import { addModelInput } from 'src/services/DataManage/type';
import TreeNode from 'src/pages/AnalyseManage/PredefinedReport/components/TreeNode';

interface listItemType {
	name: string;
	id: string;
	effect: string;
	status: string;
	code: string;
	cronData: any;
	isFile:any
}

interface IProps {
	record: listItemType;
	handleEdit: ( item: listItemType ) => void;
	handleDelete: ( item: listItemType ) => void;
	handleStart:any
	handleRoll:any
	handleUpdateFile:any
	handleExecute:any
	btnAuth:any
}

//	操作栏组件
const OperateComponent = React.memo( ( props: IProps ) => {
	return props.btnAuth.includes( 'bi_dataDispatch_action' ) ? (
		<Space size="middle">
			{
				props.record.isFile === '0'
					? (
						<>
							<Tooltip placement="topRight" title="重命名">
								<Button
									type="text" icon={ <FontSizeOutlined className={ styles.greenBtn }/> }
									onClick={ () => props.handleEdit( props.record ) }>
								</Button>
							</Tooltip>
							{
								props.record.status ==='STOPPED'
									?(
										<Tooltip placement="topRight" title={ '编辑' }>
											<Button
												type="text" icon={ <FormOutlined  className={ styles.greenBtn }/> }
												onClick={ () => props.handleRoll( props.record ) }>
											</Button>
										</Tooltip>
									
									)
									:(
										<Tooltip placement="topRight" title={ '查看' }>
											<Button
												type="text" icon={ <span  className="iconfont" style={{ fontSize: '16px',color: '#86bc25' }}>&#xe716;</span> }
												onClick={ () => {
													props.handleRoll( props.record );
													setTimeout( () => message.info( '运行中无法编辑' ),500 );
												} }>
											</Button>
										</Tooltip>
									)
							}

							<Tooltip placement="topRight" title="删除">
								<Popconfirm
									okText="确定" cancelText="取消" title="确定删除这一项？" placement="bottom"
									onConfirm={ () => props.handleDelete( props.record ) }>
									<Button type="text" icon={ <DeleteOutlined className={ styles.greenBtn }/> }>
									</Button>
								</Popconfirm>
							</Tooltip>
							<Tooltip placement="topRight" title={props.record.status ==='STOPPED'?'启动':'暂停'}>
								<Button type="text" onClick={() => props.handleStart( props.record )} icon={ props.record.status === 'STOPPED' ? <RightCircleOutlined className={ styles.greenBtn }/>
									:<StopOutlined className={ styles.greenBtn }/> }>
								</Button>
							</Tooltip>
							<Tooltip placement="topRight" title="立即执行一次">
								<Button type="text"
									disabled={props.record.status !== 'RUNNING'}
									onClick={() => props.handleExecute( props.record )}
									icon={ <SendOutlined className={ props.record.status === 'RUNNING' ? styles.greenBtn : styles.grayBtn } /> }>
								</Button>
							</Tooltip>
						</>
					)
					:(
						<>
							<Tooltip placement="topRight" title="重命名">
								<Button
									type="text" icon={ <FontSizeOutlined className={ styles.greenBtn }/> }
									onClick={() => props.handleUpdateFile( true )}>
								</Button>
							</Tooltip>
							<Tooltip placement="topRight" title="删除">
								<Popconfirm
									okText="确定" cancelText="取消" title="确定删除这一项？" placement="bottom"
									onConfirm={ () => props.handleDelete( props.record ) }>
									<Button type="text" icon={ <DeleteOutlined className={ styles.greenBtn }/> }>
									</Button>
								</Popconfirm>
							</Tooltip>
						</>
					)
			}
		</Space>
	) : (
		<Space size="middle"></Space>
	);
} );
OperateComponent.displayName = 'OperateComponent';

class DataDispatch extends React.Component<any,any> {
	//	声明当前页面变量
	state = {
		pageSize: 10,
		page: 1,
		dataList: [],
		total: 0,
		tableLoading: false,
		modalVisible: false,
		createFileVisible: false,
		editId: '',
		treeData: [],
		currentFile: '',
		selectedCodes: [], //默认选中tree
		cronData: null,
		fileData: {
			name: '',
			comments: ''
		} ,//当前文件夹
		isUpdateFile: false,
		keyWord: '',
	};

	//	列表表头配置
	columns = [
		// {
		// 	title: '编码',
		// 	dataIndex: 'code',
		// 	width: 100,
		// },
		{
			title: '数据整理名称',
			dataIndex: 'name',
			width: 200,
			render: ( text,record ) => {
				return ( <>
					{
						record.isFile === '1'
							?( <React.Fragment>
								<Typography className={styles.greenBtn} >
									<span className={ 'iconfont bdhwenjianjiadakai' } style={ { marginRight: '8px' } }></span>{text}
								</Typography>
							</React.Fragment>  )
							:( <div style={ { paddingLeft: '24px' } }><FileFilled style={ { color: '#86bc25', marginRight: '8px' } } />{text}</div> )
					}
				</> );
			}
		},
		{
			title: '描述',
			dataIndex: 'comments',
			width: 100,
		},
		{
			title: '运行状态',
			dataIndex: 'status',
			width: 100,
			render: ( text,record ) => {
				if( record.isFile !== '1' ) {
					return text ==='STOPPED'?'停止':'运行中';
				}
			}
		},
		{
			title: '创建人',
			dataIndex: 'createUser',
			width: 90,
		},
		{
			title: '最后更新人',
			dataIndex: 'modifiedUser',
			width: 90,
		},
		{
			title: '创建时间',
			dataIndex: 'createDate',
			width: 150,
		},
		{
			title: '修改时间',
			dataIndex: 'modifiedDate',
			width: 150,
		},
		/* {
			title: '生效标识',
			key: 'effect',
			width: 100,
			render: ( record: listItemType ) => {
				return (
					<Switch checked={ record.effect === 'ENABLE' } onChange={ ( value ) => this.handleActive( record, value ) }/>
				);
			}

		}, */
		{
			title: '操作',
			key: 'action',
			width: 240,
			fixed: 'right' as 'right', // typescript报错
			// eslint-disable-next-line react/display-name
			render: ( record ) => (
				<OperateComponent
					record={ record }
					handleExecute={this.handleExecute}
					handleRoll={this.handleRollChart}
					handleStart={this.handleStart}
					handleEdit={ this.handleEdit }
					handleUpdateFile={this.hanleCreateFile}
					handleDelete={ this.handleDelete }
					btnAuth={this.props.btnAuth}
				></OperateComponent>
			)

		},
	];

	modalRef: RefObject<any> = React.createRef();

	//	声明当前页面方法
	setPageSize = ( size: number ) => {
		this.setState( {
			pageSize: size
		} );
	};

	//回显
	handleRollChart = data => {
		// this.props.history.push( '/dataManage/dataArrange' );
		this.props.history.push( { pathname: '/dataManage/dataArrange', state: { ...data } } );
	}


	//	激活
	handleActive = async ( item: listItemType, value: boolean ) => {
		const data = {
			id: item.id,
			modifiedUser: '1',
			effect: value ? 'ENABLE' : 'DISABLE'
		};
		const result = await activeModel( data );
		if ( result.data && result.data.success ) {
			message.success( '操作成功' );
			this.getList();
		}
	}

	//	新增/编辑
	handleCreate = async ( data: addModelInput ) => {
		// let saveInfo;
		//	如果是编辑
		// if ( this.state.editId ) {
		// 	saveInfo = Object.assign( data,{} );
		// } else {
		// 	saveInfo = Object.assign( data, {} );
		// }
		const result = await createModel( { data: { ...data,id: this.state.editId } } );
		if ( result.data && result.data.success ) {
			this.toggleModal( false );
			message.success( '保存成功' );
			this.getList();
		}
	};

	handlePageChange = ( pageNumber: number ) => {
		this.setState( {
			page: pageNumber
		}, () => {
			this.getList();
		} );
	}

	//	打开新建组件
	toggleModal = ( isShow: boolean ) => {
		this.setState( {
			modalVisible: isShow
		} );

		if ( !isShow ) {
			this.setState( {
				editId: ''
			} );
		}
	};

	//	打开文件夹新建组件
	modalVisible = ( isShow: boolean ) => {
		this.setState( {
			createFileVisible: isShow
		} );
	};


	//	编辑
	handleEdit = ( item: listItemType ) => {
		let cronData = JSON.parse( item.cronData );
		if ( cronData && cronData.dayOfMonths && cronData.dayOfMonths.length ) {
			cronData.dayOfMonths = cronData.dayOfMonths[ 0 ];
		}
		this.setState( {
			editId: item.id,
			modalVisible: true,
			cronData,
		}, () => {
			setTimeout( () => {
				// console.log( '-----', item );
				const data = Object.assign( {}, item, this.state.cronData );
				this.modalRef.current.setFieldsValue( data );
			}, 100 );
		} );
	};

	//	删除
	handleDelete = async ( item: listItemType ) => {
		const info = await deleteModel( { data: item.id } );
		if ( info.data.success ) {
			message.success( '删除成功' );
			this.getList();
			if( item.isFile === '1' ) {
				this.getModelFiles();
			}
		}
	};

	//启动暂停
	handleStart = async ( item: listItemType ) => {
		const info = await rJob( { data: item.code } );
		if ( info.data.success ) {
			item.status === 'STOPPED' ? message.success( '启动成功' ) : message.success( '暂停成功' );
			// message.success( '删除成功' );
			this.getList();
		}
	};

	//	搜索框
	handleSearch = ( e ) => {
		// this.getList();
	};
	// 搜索框输入
	handleSearchChange = ( e ) => {
		this.setState( { keyWord: e.target.value } );
	};

	getList = async () => {
		this.setState( {
			tableLoading: true
		} );
		const info = await getArrangeList( {
			fileCode: this.state.currentFile,
			page: this.state.page,
			size: this.state.pageSize,
		} );
		if ( info.data.success ) {
			let data = this.state.page === 1?[ this.state.fileData ,...info.data.data.rows ]:info.data.data.rows;
			this.setState( {
				dataList: data,
				total: info.data.data.total
			} );
		}
		this.setState( {
			tableLoading: false
		} );
	};

	//文件夹树
	onSelect = ( event, node ) => {

	};

	//点击顶层目录
	onExpand = ( expandedKeys, { expanded: bool, node } ) => {
		this.setState( { currentFile: node.key },() => {this.getList();} );
	};

	//点击node
	clickNode = item => {
		this.setState( {
			fileData: item,
			currentFile: item.key,
		}, () => {
			this.getList();
		} );
	};

	//获取所有文件树
	getModelFiles = async () => {
		const info = await getModelTree( { data: '' } );
		if( info.data.success ) {
			this.setState( {
				treeData: info.data.data.map( item => {return { key: item.code,title: item.name,...item };} )
			} );
			if ( info.data.data.length ) {
				this.setState( {
					currentFile: this.props.location.state? this.props.location.state.id :info.data.data[0].code,
					selectedCodes: [ this.props.location.state? this.props.location.state.id:info.data.data[0].code ],
					fileData: this.props.location.state
						? info.data.data.filter( item => item.code === this.props.location.state.id )[0]
						:info.data.data[0]
				},() => {this.getList();} );
			}
		}
	}
	
	hanleCreateFile = ( t ) => {
		this.setState( {
			isUpdateFile: t
		},() => {
			setTimeout( () => {
				if( this.state.isUpdateFile ) {
					this.modalRef.current.setFieldsValue( { name: this.state.fileData.name,
						comments: this.state.fileData.comments } );
				}
			}, 100 );this.modalVisible( true );
		} );

	}

	//触发执行
	handleExecute = async ( item: listItemType ) => {
		const res = await triggerModel( { data: item.code } );
		if ( res.data.success ) {
			message.success( '执行成功!' );
		} else {
			message.error( '执行失败!' );
		}
	}


	async componentDidMount() {
		this.getModelFiles();
		
		// //	发请求获取列表
		// this.getList();
	}

	render() {
		const btnAuth = this.props.btnAuth;
		return (
			<div className={ styles.page } style={{ display: 'flex' }}>
				<div className={styles.wrap}>
					{/* <Card style={{ width: 240 }}>
						{
							this.state.treeData && this.state.treeData.length ? (
								<Tree.DirectoryTree
									className={styles.customTree}
									multiple
									defaultExpandAll
									defaultExpandedKeys={this.state.selectedCodes}
									defaultSelectedKeys={this.state.selectedCodes}
									selectedKeys={this.state.selectedCodes}
									onSelect={this.onSelect}
									onExpand={this.onExpand}
									treeData={this.state.treeData}
								/>
							) : (
								<div>暂无数据</div>
							)
						}
					</Card> */}
					<div className={styles.tree_container}>
						<p>数据模型</p>
						<div className={styles.tree_box}>
							{
								this.state.treeData.map( ( item, index: number ) => (
									<TreeNode
										activeNodeId={ this.state.currentFile } key={ index } id={ item.key }
										label={ item.title }
										handleClick={ () => this.clickNode( item ) }></TreeNode>
								) )
							}
						</div>
					</div>
				</div>
				<div className={ styles.dispatch }>
					<Row justify="space-between">
						<Col span={ 12 } style={ { textAlign: 'left' } }>
							{
								btnAuth.includes( 'bi_dataDispatch_addModel' ) && (
									<Button type='primary' icon={ <PlusCircleOutlined/> }
										onClick={ () => this.props.history.push( '/dataManage/dataArrange' )}>新建模型</Button>
								)
							}
							{
								btnAuth.includes( 'bi_dataDispatch_addFolder' ) && (
									<Button icon={ <PlusCircleOutlined/> } onClick={() => this.hanleCreateFile( false )}>新建文件夹</Button>
								)
							}
							{/*<Button icon={ <ExportOutlined/> } className='grey-button'>批量删除</Button>*/ }
						</Col>
						<Col xs={ 24 } sm={ 6 } md={ 6 } lg={ 6 } xl={ 6 } style={ { textAlign: 'right' } }>
							{/* <Input.Search placeholder="请输入" allowClear onSearch={ ( value: string ) => this.handleSearch( value ) }/> */}
							<Input placeholder="请输入模型名称回车搜索"
								allowClear 
								onChange={ this.handleSearchChange }
								onPressEnter={ this.handleSearch }
								prefix={<SearchOutlined />} />
						</Col>
					</Row>
					<Table
						// rowSelection={ { type: 'checkbox' } }
						scroll={ { x: '100%' } }
						tableLayout='fixed'
						columns={ this.columns }
						dataSource={ this.state.dataList }
						className={ styles.tableMargin }
						bordered={ true }
						rowKey={ ( row: listItemType ) => row.id }
						size='middle'
						rowClassName={ ( row ) => row.isFile === '1' ? 'row-folder' : '' }
						pagination={ {
							showSizeChanger: true,
							pageSize: this.state.pageSize,
							onChange: this.handlePageChange,
							total: this.state.total,
							onShowSizeChange: ( current, size ) => this.setPageSize( size ),
							showTotal: total => `共 ${ total } 条`,
						} }
					/>
				</div>
				
				{/*新建模板*/}
				<CreateModalComponent
					cronData={this.state.cronData}
					treeData={this.state.treeData}
					ref={ this.modalRef }
					editId={ this.state.editId }
					modalVisible={ this.state.modalVisible }
					onCreate={ this.handleCreate }
					closeModal={ this.toggleModal }/>

				{/*	新建文件夹*/}
				<CreateFile createFileVisible={this.state.createFileVisible }
					ref={ this.modalRef }
					isUpdate={this.state.isUpdateFile}
					getModelFiles={this.getModelFiles}
					fileData={this.state.fileData}
					modalVisible={this.modalVisible}/>
			</div>
		);
	}
}

//	映射state到当前组件
const mapStateToProps = ( state ) => {
	return {
		btnAuth: state.btnAuth,
	};
};

export default connect( mapStateToProps )( DataDispatch );
